package org.bandev.buddhaquotes.screens

import android.app.Activity
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Brightness6
import androidx.compose.material.icons.rounded.DarkMode
import androidx.compose.material.icons.rounded.Info
import androidx.compose.material.icons.rounded.LightMode
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.alorma.compose.settings.ui.SettingsMenuLink
import com.maxkeppeker.sheets.core.models.base.IconSource
import com.maxkeppeker.sheets.core.models.base.rememberUseCaseState
import com.maxkeppeler.sheets.option.OptionDialog
import com.maxkeppeler.sheets.option.models.Option
import com.maxkeppeler.sheets.option.models.OptionSelection
import org.bandev.buddhaquotes.R
import org.bandev.buddhaquotes.datastore.settings.Language
import org.bandev.buddhaquotes.datastore.settings.SettingsViewModel
import org.bandev.buddhaquotes.datastore.settings.toFormattedString
import org.bandev.buddhaquotes.datastore.settings.toIcon
import org.bandev.buddhaquotes.settings.Settings
import java.util.Locale

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(viewModel: SettingsViewModel =
                       SettingsViewModel(LocalContext.current)) {
    val useCaseState = rememberUseCaseState(embedded = false)
    var languageState  =rememberUseCaseState( embedded = false )

    val currentLanguage = remember {
        mutableStateOf(Language.CHINESE)
    } // 不在嵌入式环境使用
    val themeLive: Settings by viewModel.settings.observeAsState(Settings.getDefaultInstance())
    Column {
        SettingsMenuLink(
            icon = { Icon(imageVector = themeLive.theme.toIcon(), contentDescription = null) },
            title = { Text(text = stringResource(R.string.theme)) },
            subtitle = { Text(text = themeLive.theme.toFormattedString()) },
            onClick = useCaseState::show,
        )
        SettingsMenuLink(
            icon = { Icon(imageVector = Icons.Rounded.Info, contentDescription = null) },
            title = { Text(text = stringResource(R.string.language)) },
            subtitle = { Text(text = stringResource(R.string.default_language)) },
            onClick = languageState::show,
        )
    }
    OptionDialog(
        state = useCaseState,
        selection = OptionSelection.Single(
            options = listOf(
                Option(
                    icon = IconSource(Icons.Rounded.LightMode),
                    titleText = stringResource(id = R.string.light)
                ),
                Option(
                    icon = IconSource(Icons.Rounded.DarkMode),
                    titleText = stringResource(id = R.string.dark)
                ),
                Option(
                    icon = IconSource(Icons.Rounded.Brightness6),
                    titleText = stringResource(id = R.string.system)
                )
            ),
            withButtonView = false,
            onSelectOption = { index, _ ->
                viewModel.setTheme(Settings.Theme.entries.first { it.ordinal == index + 1 })
            }
        )
    )

    OptionDialog(
        state = languageState,
        selection = OptionSelection.Single(
            options = listOf(
                Option(
                    icon = IconSource(Icons.Rounded.Info),
                    titleText = "English"
                ),
                Option(
                    icon = IconSource(Icons.Rounded.Info),
                    titleText = "中文"
                ),
            ),
            withButtonView = false,  // 不显示按钮视图 ,对话框不会显示确认或取消按钮
            onSelectOption = { index, _ ->
                val index = when (index) {

                    0 -> Language.ENGLISH
                    1 -> Language.CHINESE
                    else -> {
                        Language.ENGLISH
                    }
                }
                currentLanguage .value = index ;
            }
        )
    )


    LaunchedEffect(currentLanguage.value) {
        setLanguage(currentLanguage.value , viewModel)
    }
}
fun setLanguage(language: Language, context: SettingsViewModel) {
    var locale = when (language) {
        Language.ENGLISH -> Locale("en")
        Language.CHINESE -> Locale("zh")
    }
    Log.d("SettingsViewModel", "Locale set to ${locale.language}")
    Locale.setDefault(locale)
    val resources = context.resources
//        val config = Configuration()
    val   config = resources.configuration
    config.setLocale(locale)
    resources.updateConfiguration(config, resources.displayMetrics)
    // 这里需要通知 Activity 更新其视图
    (context  as? Activity)?.recreate()

}